package com.kcsj.controller.basic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.kcsj.domain.PayType;
import com.kcsj.service.PayTypeService;
import com.kcsj.util.MessageHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

/**
 * @author 傅立贤
 * 25th Nov. 2020
 */
@WebServlet("/pay")
public class PayTypeController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端请求的信息
        String id = req.getParameter("id");
        try {
            if(id!=null){
                Integer payType_id = Integer.parseInt(id);
                this.responsePayType(resp,payType_id);
            }else {
                this.responsePayTypes(resp);
            }
        }catch (SQLException e){
            JSONObject message = MessageHelper.dateBaseError();
            resp.getWriter().println(message);
            e.printStackTrace();
        }catch(Exception e){
            JSONObject message = MessageHelper.netWordError();
            resp.getWriter().println(message);
            e.printStackTrace();
        }
    }

    private void responsePayType(HttpServletResponse response,Integer id)
            throws SQLException, IOException {
        //根据id查找学生
        PayType payType = PayTypeService.getInstance().find(id);
        String payType_json = JSON.toJSONString(payType);
        JSONObject data = MessageHelper.addData(payType_json);
        response.getWriter().println(data);
    }

    private void responsePayTypes(HttpServletResponse response) throws SQLException, IOException {
        Collection<PayType> payTypes = PayTypeService.getInstance().findAll();
        String payTypes_jsonstr = JSON.toJSONString(payTypes, SerializerFeature.DisableCircularReferenceDetect);
        JSONObject data = MessageHelper.addData(payTypes_jsonstr);
        //响应resp_jsonObj到前端
        response.getWriter().println(data);
    }

}
